#!/usr/bin/env python
# coding=utf-8
# @Time    : 2021/12/26
# @Author  : 秋天的落寞

import configparser
from loguru import logger
from netmiko import ConnectHandler, NetmikoAuthenticationException, NetmikoTimeoutException


def Login_device(IP, user, passwd, dev_type):
    """
    登陆设备
    :param dev_type: 设备类型
    :param IP: 设备IP地址
    :param user: 用户名
    :param passwd: 密码
    :return: 登陆设备后的ssh长连接
    """
    try:
        device = {
            "device_type": dev_type,  # "hp_comware（H3C平台）", 网络设备类型
            "ip": IP,  # IP地址
            "username": user,  # 设备登陆账号
            "password": passwd  # 设备登陆密码
        }
        connect = ConnectHandler(**device)
        return connect
    except NetmikoAuthenticationException:
        logger.error(f"[-] {IP} 登陆认证失败，账号密码可能错误！")
    except NetmikoTimeoutException:
        logger.error(f"[-] 登陆超时，请确认({IP})网络是否正常或IP是否存在")
    except Exception as f:
        logger.error(f)


def ssh_user_passwd() -> list:
    """
    :return: ssh账号密码
    """
    try:
        users_file_ssh = configparser.ConfigParser()
        users_file_ssh.read("user_pass.ini")
        user = users_file_ssh.get("SSH", "user")
        passwd = users_file_ssh.get("SSH", "password")
        if user and passwd:
            return [user, passwd]
        return []
    except Exception as f:
        logger.error(f)


def telnet_user_passwd() -> list:
    """
    :return: telnet账号密码
    """
    try:
        users_file_tel = configparser.ConfigParser()
        users_file_tel.read("user_pass.ini")
        user = users_file_tel.get("TELNET", "user")
        passwd = users_file_tel.get("TELNET", "password")
        if user and passwd:
            return [user, passwd]
        return []
    except Exception as f:
        logger.error(f)
